"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : SQL引擎插件
Case Name   : 先连接加载插件的B类型数据库，再切到另一个加载插件的B数据库，
              再切到第一个加载插件的B类型数据库，执行业务操作
Create At   : 2022.04.12
Owner       : z@wan005
Description :
    1.创建b库
    2.连接b库查询插件是否存在
    3.兼容b库下创建测试用户和表
    4.兼容b库下给表插入大量数据
    5.切换至另一个兼容B库建表
    6.切回第一个b库删除表数据
    7.修改线程池参数为on
    8.兼容b库且有插件给表插入大量数据
    9.切换至另一个兼容B库建表
    10.切回第一个b库删除表数据
    11.清理环境
Expect      :
     1.成功
     2.成功
     3.插件自动加载
     4.成功
     5.成功
     6.成功
     6.成功
     7.成功
     8.成功
     9.成功
     10.成功
     11.成功
History     :modified by z@wan005,2022.08.29，om数据库目前实现自动加载dolphin插件，
             因此删除用例中拷贝插件依赖文件步骤
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class PluginTest022(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.common = Common()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.us_name = "us_plugin0022"
        self.tb_name = "tb_plugin0022"
        self.tb_name_01 = "tb_plugin0022_01"
        self.db_name = "db_plugin0022"
        self.db_name_01 = "db_plugin0022_01"
        self.default_value = self.common.show_param('enable_thread_pool')
        sql_res = self.pri_sh.execut_db_sql('alter system set '
                                            'enable_thread_pool to off;')
        self.log.info(sql_res)
        restart_msg = self.pri_sh.restart_db_cluster()
        self.log.info(restart_msg)

    def test_dolphin(self):
        text = '----step1:创建b库;expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} DBCOMPATIBILITY ='b';" \
                  f"drop database if exists {self.db_name_01};" \
                  f"create database {self.db_name_01} DBCOMPATIBILITY ='b';"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertEquals(2,
                          sql_res.count(self.constant.CREATE_DATABASE_SUCCESS),
                          '执行失败' + text)

        text = '--step2:连接b库查询插件是否存在;expect:插件自动加载---'
        self.log.info(text)
        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd, dbname=self.db_name)
        self.log.info(sql_res)
        self.assertEqual('dolphin', sql_res.splitlines()[-2].strip(),
                         '执行失败' + text)
        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd,
                                            dbname=self.db_name_01)
        self.log.info(sql_res)
        self.assertEqual('dolphin', sql_res.splitlines()[-2].strip(),
                         '执行失败' + text)

        text = '--step3:兼容b库下创建测试用户和表;expect:成功-----'
        self.log.info(text)
        cmd = f'''drop user if exists {self.us_name};\
        create user {self.us_name} with sysadmin  password \
        '{macro.PASSWD_INITIAL}';     
        drop table if  exists {self.tb_name};\
        create table {self.tb_name} \
        (id int, name text(10));'''
        result = self.pri_sh.execut_db_sql(cmd, dbname=self.db_name)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result,
                      '执行失败' + text)

        text = '---step4:兼容b库下给表插入大量数据;expect:成功-----'
        self.log.info(text)
        create_cmd = f'''insert into {self.tb_name} values \
        (generate_series(1,1000000), 'col'|| generate_series(1,1000000));'''
        res = self.pri_sh.execut_db_sql(sql=create_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res,
                      '执行失败' + text)

        text = '---step5:切换至另一个兼容B库建表;expect:成功-----'
        self.log.info(text)
        create_cmd = f'''drop table if  exists {self.tb_name};\
        create table {self.tb_name} (id int, name text(10), salary double);'''
        res = self.pri_sh.execut_db_sql(sql=create_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name_01)
        self.log.info(res)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result,
                      '执行失败' + text)

        text = '---step6:切回第一个b库删除表数据;expect:成功-----'
        self.log.info(text)
        delete_cmd = f'''delete {self.tb_name};'''
        res = self.pri_sh.execut_db_sql(sql=delete_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, res,
                      '执行失败' + text)

        text = '---step7:修改线程池参数为on;expect:成功-----'
        self.log.info(text)
        cmd = f'alter system set enable_thread_pool to on;'
        result = self.pri_sh.execut_db_sql(cmd)
        self.log.info(result)
        restart_msg = self.pri_sh.restart_db_cluster()
        self.log.info(restart_msg)

        text = '---step8:兼容b库且有插件给表插入大量数据;expect:成功-----'
        self.log.info(text)
        insert_cmd = f'''insert into {self.tb_name} values \
               (generate_series(1,1000000), 'col'|| \
               generate_series(1,1000000));'''
        res = self.pri_sh.execut_db_sql(sql=insert_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res,
                      '执行失败' + text)

        text = '---step9:切换至另一个兼容B库建表;expect:成功-----'
        self.log.info(text)
        create_cmd = f'''drop table if  exists {self.tb_name};\
               create table {self.tb_name} (id int, name text(10));'''
        res = self.pri_sh.execut_db_sql(sql=create_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name_01)
        self.log.info(res)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, res,
                      '执行失败' + text)

        text = '---step10:切回第一个b库删除表数据;expect:成功-----'
        self.log.info(text)
        create_cmd = f'''delete {self.tb_name};'''
        res = self.pri_sh.execut_db_sql(sql=create_cmd,
                                        sql_type=f'-U {self.us_name} '
                                                 f'-W {macro.PASSWD_INITIAL}',
                                        dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, res,
                      '执行失败' + text)

    def tearDown(self):
        text = '---step11:清理环境; expect:清理环境成功-----'
        self.log.info(text)
        self.log.info('删除数据库')
        cmd = f"drop database if exists {self.db_name};" \
              f"drop database if exists {self.db_name_01}"
        result = self.pri_sh.execut_db_sql(cmd)
        self.log.info('删除用户')
        cmd = f"drop user if exists {self.us_name};"
        drop_result = self.pri_sh.execut_db_sql(cmd)
        self.log.info(drop_result)
        self.log.info('恢复参数默认值')
        self.pri_sh.execute_gsguc(
            "set", self.constant.GSGUC_SUCCESS_MSG,
            f"enable_thread_pool = {self.default_value}")
        self.pri_sh.restart_db_cluster()
        self.assertEquals(2,
                          result.count(self.constant.DROP_DATABASE_SUCCESS),
                          '执行失败' + text)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_result,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
